package com.atguigu.tingshu.payment.service.impl;

import cn.hutool.core.lang.Assert;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.account.RechargeInfo;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.payment.PaymentInfo;
import com.atguigu.tingshu.order.client.OrderFeignClient;
import com.atguigu.tingshu.payment.mapper.PaymentInfoMapper;
import com.atguigu.tingshu.payment.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@SuppressWarnings({"all"})
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {
    @Autowired
    private OrderFeignClient orderFeignClient;
    @Autowired
    private AccountFeignClient accountFeignClient;
    @Override
    public PaymentInfo savePaymentInfo(String orderNo, String paymentType, Long userId) {
        //查询是否记录
        QueryWrapper<PaymentInfo> eq = new QueryWrapper<PaymentInfo>().eq("order_no", orderNo).eq("user_id", userId).eq("payment_type", paymentType);
        Long l = baseMapper.selectCount(eq);
        PaymentInfo paymentInfo = new PaymentInfo();
        if (l > 0) {

            throw new GuiguException(400, "支付记录已存在");
        } else {

            paymentInfo.setOrderNo(orderNo);
            paymentInfo.setPaymentType(paymentType);
            paymentInfo.setUserId(userId);
            paymentInfo.setPayWay(SystemConstant.ORDER_PAY_WAY_WEIXIN);
            paymentInfo.setOutTradeNo(orderNo.substring(10, 19));

            paymentInfo.setPaymentStatus(SystemConstant.PAYMENT_STATUS_UNPAID);
            if (SystemConstant.PAYMENT_TYPE_RECHARGE.equals(paymentType)) {
                //充值订单向rechargeinfo中添加数据
                RechargeInfo data = accountFeignClient.getRechargeInfo(orderNo).getData();
                Assert.notNull(data, "充值订单不存在");
                paymentInfo.setAmount(data.getRechargeAmount());
                paymentInfo.setContent("充值金额：" + data.getRechargeAmount() + "元");
            }else if (SystemConstant.PAYMENT_TYPE_ORDER.equals(paymentType)) {
                //购买订单向orderinfo中添加数据
                OrderInfo data = orderFeignClient.getOrderInfo(orderNo).getData();
                Assert.notNull(data, "订单不存在");
                paymentInfo.setAmount(data.getOrderAmount());
                paymentInfo.setContent(data.getOrderTitle());


            }
            baseMapper.insert(paymentInfo);
        }

        return paymentInfo;
    }
}
